package com.juphoon.mockdata.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.juphoon.mockdata.data.db.ResponseDO;
import com.juphoon.mockdata.data.dto.BaseResponseDTO;
import com.juphoon.mockdata.data.dto.E06RequestDTO;
import com.juphoon.mockdata.mapper.ResponseMapper;
import com.juphoon.mockdata.service.IResponseService;
import com.juphoon.mockdata.util.XmlHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.nio.charset.StandardCharsets;

@Service
public class E06ResponseServiceImpl implements IResponseService {

    @Autowired
    private ResponseMapper responseMapper;


    @Override
    public void deal(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, String content) {
        try {
            E06RequestDTO.Common e06RequestDTO = new XmlHelper().fromXml(content, E06RequestDTO.Common.class);
            QueryWrapper<ResponseDO> wrapper = new QueryWrapper<>();
            wrapper.eq("input1", e06RequestDTO.getSys_head().getServiceCode());
            wrapper.eq("input2", e06RequestDTO.getSys_head().getServiceScene());
            wrapper.eq("input3", e06RequestDTO.getSys_head().getServiceVersion());
            ResponseDO responseDO = responseMapper.selectOne(wrapper);
            String outputClass = responseDO.getOutputClass();
            BaseResponseDTO responseDTO = (BaseResponseDTO) Class.forName(outputClass).newInstance();
            String responseDTOXml = responseDTO.genData();
            httpServletResponse.getOutputStream().write((responseDTOXml).getBytes(StandardCharsets.UTF_8));
        } catch (IOException e) {
            throw new RuntimeException(e);
        } catch (ClassNotFoundException e) {
            throw new RuntimeException(e);
        } catch (IllegalAccessException e) {
            throw new RuntimeException(e);
        } catch (InstantiationException e) {
            throw new RuntimeException(e);
        }
    }
}
